package ecom.stateless;


import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Queue;
import javax.jms.Topic;
import javax.jms.Connection;
import javax.jms.Session;
import javax.jms.MessageProducer;
import javax.jms.TextMessage;
import javax.jms.JMSException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.annotation.Resource;

public class Producer {
	//@Resource(mappedName = "jms/ConnectionFactory")
    private  ConnectionFactory connectionFactory;
    //@Resource(mappedName = "jms/Queue")
    private  Queue queue;
    
    Connection connection = null;
    Destination dest = null ;
    final int NUM_MSGS = 1;
    
    
    void createProducer(String mail, String titre) throws NamingException
    {

    try{
   
    		try{
    	    	InitialContext initCtx = new InitialContext();
    	        // Perform JNDI lookup to obtain the resource.
    	    	queue = (Queue)
    	    			initCtx.lookup("sampleQueue");
    	    	}catch(Exception e)
    	    	{
    	    		System.out.println("got Exception 2" + e.getMessage());
    	    	}
    	
    	
    	dest = (Destination) queue;
   
    	
    		
    		
    		try{
    	    	InitialContext initCtx = new InitialContext();
    	        // Perform JNDI lookup to obtain the resource.
    	    	connectionFactory = (ConnectionFactory)
    	    			initCtx.lookup("CF");
    	    	}catch(Exception e2)
    	    	{
    	    		System.out.println("got Exception 2" + e2.getMessage());
    	    	}
    		
    	
    	
    	
        connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(
                    false,
                    Session.AUTO_ACKNOWLEDGE);

        MessageProducer producer = session.createProducer(dest);
        TextMessage message = session.createTextMessage();  
            message.setText(mail+ " "+ titre);
            System.out.println("Sending message: " + message.getText());
            producer.send(message);
      

        /*
         * Send a non-text control message indicating end of
         * messages.
         */
        //producer.send(session.createMessage());
    } catch (JMSException e) {
        System.err.println("Exception occurred: " + e.toString());
    } finally {
//        if (connection != null) {
//            try {
//                connection.close();
//            } catch (JMSException e) {
//            }
//        }
    }
    }
    
}
